#include "../libs/inih/ini.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
	char app_name[50];	 // 应用程序名称
	int app_port;		 // 应用程序端口
	char redis_host[50]; // Redis主机
	int redis_port;		 // Redis端口
} config;

// 处理程序函数，用于处理每一行读取的数据
static int handler(void *user, const char *section, const char *name,
				   const char *value) {
	config *pconfig = user;
	if (strcmp(section, "app") == 0) {
		if (strcmp(name, "name") == 0) {
			strncpy(pconfig->app_name, value, sizeof(pconfig->app_name));
		} else if (strcmp(name, "port") == 0) {
			pconfig->app_port = atoi(value);
		}
	} else if (strcmp(section, "redis") == 0) {
		if (strcmp(name, "host") == 0) {
			strncpy(pconfig->redis_host, value, sizeof(pconfig->redis_host));
		} else if (strcmp(name, "port") == 0) {
			pconfig->redis_port = atoi(value);
		}
	}
	return 1;
}

static int inih_example() {
	config cfg;
	strncpy(cfg.app_name, "default", sizeof(cfg.app_name));
	cfg.app_port = 0;
	strncpy(cfg.redis_host, "localhost", sizeof(cfg.redis_host));
	cfg.redis_port = 0;

	// 解析INI文件
	if (ini_parse("etc/config.ini", handler, &cfg) < 0) {
		printf("Cannot load 'cfg.ini'\n");
		return 1;
	}

	// 打印读取的配置数据
	printf("App Name: %s\n", cfg.app_name);
	printf("App Port: %d\n", cfg.app_port);
	printf("Redis Host: %s\n", cfg.redis_host);
	printf("Redis Port: %d\n", cfg.redis_port);
	return 0;
}
